<?php
/* explain:
 * 
 * @ link 		http://www.marsemd.com/
 * @ Email		ldmmyx@hotmail.com
 * @ copyright 	2005  ivan Ling Deming	
 * @ author 	gaby  ivan Ling Deming
 * @ version 2.0
 *
 */
include_once("DB.php");
class Session extends DB 
{
	private $s_link;
	private $execInfo;
	private $sessionID;
	private $session   				= array();
	private $varCookie 				= array();
	private $varServer 				= array();
	private $arrDomain 				= array();	
	private $session_cfg 			= array();	
	private $session_existed 		= false;	
	private $session_data_max_len 	= 255;
	
	private $session_table_name 	= '';
	
	function Session($DBTag = 'system', $sessionTableName = 'sessionheap')
	{
		$this->sessionID					= '';
		
		$this->session_cfg["pconnect"] 		= false;
		$this->session_cfg['expires'] 		= 1800;		//--> expire unit: second
		$this->session_cfg['cookie_name']	= 'SESSION_ID';
		$this->session_cfg['cookie_path']	= '/';
		$this->session_cfg['cookie_domain']	= '';
		
		$this->session_table_name			= $sessionTableName;
		
		parent::DB();
		$this->s_link = $this->getConnection($DBTag);
		
		if($this->s_link){
			$sql = "CREATE TABLE IF NOT EXISTS " . $this->session_table_name . " (
				    session_id 			CHAR(32) NOT NULL,
				   	userid				int(11) unsigned NOT NULL default '0',
				    start_time 			timestamp NOT NULL,
				    last_active_time 	timestamp NOT NULL,
				    session_data 		CHAR(255) NOT NULL DEFAULT '',
				    PRIMARY KEY 		(session_id),
				    UNIQUE sessionid_time (session_id, last_active_time)) TYPE=HEAP";
    		$rs  = mysql_query($sql,$this->s_link);  
		}
		$this->init();
	}
	
	/* Session
	 * 
	 * @param  array  	arrDomain  
	 * @param  int 			expires
	 */
	public function init($arrDomain = ARR_DOMAIN, $expires = INT_EXPIRES)
	{
		if(!empty($expires))
			$this->session_cfg['expires'] = $expires;//--> timeout

		if(!empty($arrDomain)){
			$arrtmp = explode(",",$arrDomain);
			if(in_array("127.0.0.1", $arrtmp) || in_array("localhost", $arrtmp)){
				foreach ($arrtmp as $value){
					if($value != '127.0.0.1' && $value != 'localhost')
						$this->arrDomain[] = $value;
				}
			}else
				$this->arrDomain = $arrtmp;
		}
	}

	/* session
	 * 
	 * @param  return int 1: true  0: false
	 */
	public function exist()
	{  
		if($this->session_existed)
			return true;
			
		if(!is_resource($this->s_link)) 
			return 0;
		
		global $_COOKIE,$_SERVER;
		
		$this->varCookie = $_COOKIE;
		$this->varServer = $_SERVER;
		$this->sessionID = isset($this->varCookie[$this->session_cfg['cookie_name']]) ? $this->varCookie[$this->session_cfg['cookie_name']] : ''; 
		
		if($this->sessionID == ''){
			$this->session_existed = false;
			return 0;
		}else{ 
			$sql = "SELECT * FROM " . $this->session_table_name . " WHERE session_id='".$this->sessionID."' AND last_active_time>date_sub(now(),INTERVAL ".$this->session_cfg['expires']." SECOND)";

			$rs = mysql_query($sql, $this->s_link) or die (mysql_error()); 
			if(mysql_num_rows($rs) == 0){	
				$this->session_existed=false;
				$this->execInfo='session timeout.';
				return 0;
			}else{ 
				$arrBack=mysql_fetch_array($rs);
				$this->session = unserialize($arrBack['session_data']);
				$this->session['uid']	  		   = $arrBack['userid']; 
				$this->session['start_time']	   = $arrBack['start_time']; 
				$this->session['last_active_time'] = $arrBack['last_active_time']; 
				
				$domainCount = count($this->arrDomain);
				if($domainCount > 0){
					if(strlen($this->session_cfg['cookie_name']) > 0)
						setcookie($this->session_cfg['cookie_name'],$this->sessionID, time() + $this->session_cfg['expires'] ,$this->session_cfg['cookie_path'],$this->session_cfg['cookie_domain']); 
					for($i=0; $i < $domainCount; $i++)
						setcookie($this->session_cfg['cookie_name'],$this->sessionID, time() + $this->session_cfg['expires'] ,$this->session_cfg['cookie_path'],$this->arrDomain[$i]); 
				}else if(strlen($this->session_cfg['cookie_domain']) > 0)
					setcookie($this->session_cfg['cookie_name'],$this->sessionID, time() + $this->session_cfg['expires'], $this->session_cfg['cookie_path'],$this->session_cfg['cookie_domain']); 
						
				$this->session_existed = true;
				register_shutdown_function(array(&$this,"save"));
				return 1;
			} 
		}
	} 
		
	/*
	 * 
	 * @param  int 	  userid  	
	 * @param  string session_data
	 * @param  return array 
	 */
	public function start($userid = 0, $session_data = array())
	{  
		if(!is_resource($this->s_link)) 
			return 0;
		
		$strSessionData = addslashes(serialize($session_data));
		if(strlen($strSessionData) > $this->session_data_max_len) 
			return 0;
		
		$this->sessionID	= md5(uniqid(rand()));
		$domainCount		= count($this->arrDomain);
		if($domainCount > 0){
			if(strlen($this->session_cfg['cookie_name']) > 0)
				setcookie($this->session_cfg['cookie_name'],$this->sessionID, time() + $this->session_cfg['expires'] ,$this->session_cfg['cookie_path'],$this->session_cfg['cookie_domain']); 
			for($i=0; $i < $domainCount; $i++)
				setcookie($this->session_cfg['cookie_name'],$this->sessionID, time() + $this->session_cfg['expires'] ,$this->session_cfg['cookie_path'],$this->arrDomain[$i]); 
		}else if(strlen($this->session_cfg['cookie_domain']) > 0)
			setcookie($this->session_cfg['cookie_name'],$this->sessionID, time() + $this->session_cfg['expires'], $this->session_cfg['cookie_path'],$this->session_cfg['cookie_domain']); 

		$sql = "INSERT INTO " . $this->session_table_name . " SET userid=$userid, session_id='".$this->sessionID."', start_time=now(), last_active_time=now(), session_data='".$strSessionData."'";
		
		$rs  = mysql_query($sql, $this->s_link) or die($sql . ': ' .mysql_error($this->s_link));  
		
		if($rs){
			$this->session						= $session_data;
			$this->session['uid']				= $userid;
			$this->session['start_time']		= date('Y-m-d H:i:s');	
			$this->session['last_active_time']	= date('Y-m-d H:i:s'); 							
			$this->session_existed				= true;
			
			return $this->session;
		}else{
			$this->session_existed=false;
			
			return 0;
		}
	}
	
	public function getUserID()
	{
		return $this->session['uid'];
	}
	
	public function getGroupID()
	{
		return $this->session['gid'];
	}
	
	public function getUserName()
	{
		return $this->session['uname'];
	}
	
	public function getStartTime()
	{
		return $this->session['start_time'];
	}
	
	public function getLastActiveTime()
	{
		return $this->session['last_active_time'];
	}
	
	public function getData()
	{
		return $this->session;
	}
	
	public function getSessionID()
	{
		return $this->sessionID;
	}
	
	public function getLanguage()
	{
		return $this->session['lan'];
	}
	
	public function getLoginID()
	{
		return $this->session['login_id'];
	}
	
	/*
	 *
	 *
	 * @param  return int
	 */
	public function save()
	{ 
		if(!is_resource($this->s_link))
			return 0;

		$this->kill_timeout();
		if($this->session_existed){	
			unset($this->session['start_time']);
			unset($this->session['last_active_time']);
			unset($this->session['uid']);
			
			$strSessionData=addslashes(serialize($this->session));
			if(strlen($strSessionData) > $this->session_data_max_len)
				return 0;
			else{
				$sql = "UPDATE " . $this->session_table_name . " SET session_data='".$strSessionData."',last_active_time=now() where session_id='".$this->sessionID."'"; // �� ���� session��ݡ�
				$rs  = mysql_query($sql,$this->s_link);  
				if($rs)
					return 1;
				else
					return 0;
			}
		}else
			return 0;
	} 
	/*
	 *
	 * @param  array session_data
	 * @param  return int
	 */
	public function add($session_data = array())
	{ 
		if(!is_resource($this->s_link)) 
			return 0;

		if($this->session_existed){
			$arrSessionTmp   = $this->session;
			unset($arrSessionTmp['uid']); 	
			unset($arrSessionTmp['start_time']);
			unset($arrSessionTmp['last_active_time']);
			$arrSessionTmp  = array_merge($arrSessionTmp,$session_data);
			$strSessionData = addslashes(serialize($arrSessionTmp));
			
			
			if(strlen($strSessionData) > $this->session_data_max_len)
				return 0;
			else{
				$sql = "UPDATE " . $this->session_table_name . " SET session_data='".$strSessionData."',last_active_time=now() WHERE session_id='".$this->sessionID."'"; // �� ����session��ݡ�
				$rs  = mysql_query($sql,$this->s_link);
				if($rs){
					$this->session['last_active_time']	= date('Y-m-d H:i:s'); 	
					$this->session = $arrSessionTmp;
					return 1;
				}else
					return 0;
			}
		}else
			return 0;
	} 
	/* session_destroy()
	 * 
	 * @param  return int
	 */
	public function destroy()
	{ 
		if(!is_resource($this->s_link)) 
			return 0;

		$rs = mysql_query("DELETE FROM " . $this->session_table_name . " WHERE session_id='".$this->sessionID."'",$this->s_link);
		if($rs)
			return 1;
		else
			return 0;
	}
	/* 
	 *
	 * @param  return int
	 */
	public function kill_timeout()
	{ 
		if(!is_resource($this->s_link)) 
			return 0;

		$result = mysql_query("DELETE FROM " . $this->session_table_name . " WHERE last_active_time<DATE_SUB(now(),interval ".$this->session_cfg['expires']." SECOND)",$this->s_link);
		if($result)
			return 1;
		else
			return 0;
	} 
}
?>
